package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.BaseDbTableProcess;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.*;
import java.util.*;

/**
 * @author Felix
 * @date 2023/12/23
 */
public class BaseDbTableProcessFunction extends BroadcastProcessFunction<JSONObject, String, JSONObject> {

    private MapStateDescriptor<String, BaseDbTableProcess> mapStateDescriptor;

    private Map<String, BaseDbTableProcess> configMap = new HashMap<>();

    public BaseDbTableProcessFunction(MapStateDescriptor<String, BaseDbTableProcess> mapStateDescriptor) {
        this.mapStateDescriptor = mapStateDescriptor;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        //将配置表中配置信息提前预加载到程序中
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall0710_config?" +
            "user=root&password=123456&useUnicode=true&" +
            "characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");
        String sql = "select * from gmall0710_config.table_process_dwd";

        //获取数据库操作对象
        PreparedStatement ps = conn.prepareStatement(sql);
        //执行sQL语句
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        //处理结果集
        while (rs.next()) {
            JSONObject jsonObj = new JSONObject();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);
                jsonObj.put(columnName, columnValue);
            }
            BaseDbTableProcess tableProcess = JSON.toJavaObject(jsonObj, BaseDbTableProcess.class);
            String sourceTable = tableProcess.getSourceTable();
            String type = tableProcess.getSourceType();
            String key = sourceTable + ":" + type;
            configMap.put(key, tableProcess);
        }

        //释放资源
        rs.close();
        ps.close();
        conn.close();
    }

    //处理主流数据   jsonObj:{"database":"","table":"","type":"","data":{},"old":{},"ts":""}
    @Override
    public void processElement(JSONObject jsonObj, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        //获取操作的业务数据库表的表名
        String table = jsonObj.getString("table");
        //获取对数据库表进行的操作的类型
        String type = jsonObj.getString("type");
        //根据表名和操作类型拼接key
        String key = table + ":" + type;
        //获取广播状态
        ReadOnlyBroadcastState<String, BaseDbTableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //根据key到广播状态以及configMap中获取对应的配置信息
        BaseDbTableProcess tableProcess = null;

        //如果配置信息不为空，说明是需要动态分流处理的事实表  将数据传递到下游
        if((tableProcess = broadcastState.get(key))!= null
                || (tableProcess = configMap.get(key))!= null){

            //只需要传递data部分内容即可
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");

            //在向下游传递数据前，过滤掉不需要传递的字段
            String sinkColumns = tableProcess.getSinkColumns();
            filterColumn(dataJsonObj,sinkColumns);
            //在向下游传递数据前，补充输出到kafka的目的地
            String sinkTable = tableProcess.getSinkTable();
            dataJsonObj.put("sink_table",sinkTable);
            //在向下游传递数据前，补充事件时间
            Long ts = jsonObj.getLong("ts");
            dataJsonObj.put("ts",ts);

            out.collect(dataJsonObj);
        }
    }

    //过滤掉不需要传递的字段
    private void filterColumn(JSONObject dataJsonObj, String sinkColumns) {
        List<String> columnList = Arrays.asList(sinkColumns.split(","));
        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry->!columnList.contains(entry.getKey()));
    }

    //处理广播流数据  jsonStr:{"before":{},"after":{},"op":"crud"}
    @Override
    public void processBroadcastElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
        //为了处理方便，将jsonStr转换为jsonObj
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        //获取对配置表进行的操作的类型
        String op = jsonObj.getString("op");
        //获取广播状态
        BroadcastState<String, BaseDbTableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        if("d".equals(op)){
            //从before属性中获取配置表中的信息
            BaseDbTableProcess before = jsonObj.getObject("before", BaseDbTableProcess.class);
            //将配置信息从广播状态以及configMap中删除掉
            String sourceTable = before.getSourceTable();
            String type = before.getSourceType();
            String key = sourceTable + ":" + type;
            broadcastState.remove(key);
            configMap.remove(key);
        }else{
            //从after属性中获取配置表中的信息
            BaseDbTableProcess after = jsonObj.getObject("after", BaseDbTableProcess.class);
            //将最新的配置信息更新到广播状态以及configMap中
            String sourceTable = after.getSourceTable();
            String sourceType = after.getSourceType();
            String key = sourceTable + ":" + sourceType;
            broadcastState.put(key,after);
            configMap.put(key,after);
        }

    }
}
